class Ster {
  constructor() {
    this.getStr();
  }
  async getStr() {
    let { data, status } = await axios.get('http://localhost:8888/goods/list')
    if (status != 200 || data.code != 1) return;
    let html = '';
    data.list.forEach(goods => {
      console.log(goods);
      html += `<li class="sk_goods">
      <a href="./detail.html?id=${goods.goods_id}"><img src="${goods.img_big_logo}" alt=""></a>
      <h5 class="sk_goods_title">${goods.title}</h5>
      <p class="sk_goods_price"><em>¥${goods.price}</em> <del>￥${goods.current_price}</del></p>
      <div class="sk_goods_progress">
          已售<i>${goods.sale_type}</i>
          <div class="bar">
              <div class="bar_in"></div>
          </div>
          剩余<em>${goods.goods_number}</em>件
      </div>
      <a href="#none" class="sk_goods_buy" onclick="Ster.nowBuy(${goods.goods_id})">立即抢购</a>
  </li>`;

    });
    this.$('.sk_bd ul').innerHTML = (html+html+html+html);
    console.log();

  }
  // 加入购物车
  static nowBuy(goodsId) {
    //判断token有无失效
    let token = localStorage.getItem('token');
    if (!token) location.assign('./login.html?./list.html');

    let userId = localStorage. getItem('user_id');
    let param = `id=${userId}&goodsId=${goodsId}`;
    // 商品id
    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.common['Authorization'] = token;
    axios.post('http://localhost:8888/cart/add', param).then(res => {
      let { status, data } = res;
      // 判断服务器状态  
      if (status != 200) throw new Error("老铁能不能睁开眼看看!");
      if (data.code == 0) location.href = './login.html';
      // console.log(data);
      // 提示下一步的操作
      layer.confirm('还买吗老铁?', {
        btn: ['买!', '不败家了'] //按钮
      }, function () {
        location.href = './cart.html'; 
      });
    })
  }
  // 获取节点的方法
  $(ele) {
    let res = document.querySelectorAll(ele);
    return res.length == 1 ? res[0] : res;
  }
}

new Ster;